function convertStructureRecursive(input: any[]) {
	let origin: any = {
		data: {
			text: "内容大纲",
			uid: "001",
			expand: true,
		},
		children: [],
	}

	const generateChildren = (origin: any, children: any[]) => {
		for (let item of children) {
			if (item) {
				let child: any = {
					data: {
						text: item.text,
						uid: item.id,
						expand: true,
					},
					children: [],
				}

				if (item.children && item.children.length > 0) {
					child = generateChildren(child, item.children)
				}

				origin.children.push(child)
			}
		}
		return origin
	}

	const result = generateChildren(origin, input)

	return result
}

export type DirItem = {
	id: string
	tag: "h2" | "h3" | "h4" | "h5"
	text: string
	children?: DirItem[]
}

const getHeadTree = (dir: DirItem[]) => {
	const dest: any = []
	let curH2 = -1
	let curH3 = -1
	let curH4 = -1
	dir.forEach((v, i) => {
		if (v.tag === "h2") {
			curH2++
			dest[curH2] = { ...v, children: [] }
			return
		}
		if (v.tag === "h3" && curH2 > -1) {
			curH3++
			dest[curH2].children[curH3] = { ...v, children: [] }
			return
		}
		if (v.tag === "h4" && curH2 > -1 && curH3 > -1) {
			curH4++
			dest[curH2].children[curH3].children[curH4] = { ...v, children: [] }
			return
		}
		if (v.tag === "h5" && curH2 > -1 && curH3 > -1 && curH4 > -1) {
			dest[curH2].children[curH3].children[curH4].children.push({ ...v })
		}
	})
	const cleanTree = (node: DirItem): DirItem => {
		if (node.children) {
			node.children = node.children.filter((child) => child !== null)
			node.children = node.children.map(cleanTree)
		}
		return node
	}
	return dest.map(cleanTree)
}

export { convertStructureRecursive, getHeadTree }
